package com.bookstore.service;

import com.bookstore.entity.Book;
import com.bookstore.entity.Comments;
import com.bookstore.mapper.CommentsMapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CommentService {
    @Autowired
    CommentsMapper mapper;

    public int updateShow(Integer show,String commentId){
        int update= mapper.updateShow(show,commentId);
        return update;
    }


    /**
     * 获取评论平且分类
     */
    public PageInfo<Comments> getCommentsByPage(int pageNum, int pageSize) {
        Page<Comments> page = PageHelper.startPage(pageNum, pageSize);
        int pageEnd = pageNum + pageSize;
        //分页处理，显示第一页的10条数据
        PageHelper.startPage(pageNum, pageSize);
        List<Comments> comments = mapper.getCommentsByPage((pageNum-1)*pageSize, pageSize*pageNum);
        // 取分页信息
        PageInfo pageInfo = new PageInfo<Book>();
        //总的记录数
        Integer total = mapper.countComments();
        Integer number = total/pageSize;
        number += total%pageSize>0?1:0;
        pageInfo.setTotal(total);
        pageInfo.setPages(number);
        pageInfo.setList(comments);
        return pageInfo;
    }

    /**
     * 根据书籍ID分页获取评论
     * @param pageNum
     * @param pageSize
     * @param bookId 图书id
     * @return
     */
    public PageInfo<Comments> getAllCommentsByBookId(Integer pageNum,Integer pageSize,String bookId){
        PageHelper.startPage(pageNum,pageSize);
        List<Comments> commentsList = mapper.getCommentsByBookId(bookId);
        PageInfo<Comments> pageInfo = new PageInfo<Comments>(commentsList);
        return pageInfo;
    }

    @Transactional
    public boolean addComment(Comments comments){
        try {
            mapper.insertSelective(comments);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除评论
     */
    @Transactional
    public boolean delComments(String commentId){
        int comments = mapper.delComments(commentId);
        if (comments>0){
            return true;
        }else{
            return false;
        }
    }

}
